<?php
date_default_timezone_set('Europe/Berlin');
$moduleName = @$_GET['module'];
$resAsFile = @$_GET['file'];
$size = @$_GET['size'];
$online = @$_GET['online'];

$stringForm = '<html><head><title>Mini logo generator</title></head><body><h1>Mini logo generator</h1><div style="border:1px solid #FF0000;color:#FF0000;font-weight:bold;padding:5px;">%error%</div><p>Generation of the mini logo based on the 100px logo that should be located in module/ressources/logo.png</p><p><b>ModuleName</b>:<form><input type="text" name="module" value="%moduleName%"></input><br /><select name="size"><option value="28">28</option><option value="26">26</option><option value="24">24</option></select><br /><input type="checkbox" name="file">result as a file</input><br /><input type="submit"></input></form></p><h3>Image</h3>%image%</body></html>';

if(!$moduleName) {
	echo preg_replace(array('/%moduleName%/','/%error%/','/%image%/'),array('','',''),$stringForm);
	return;	
}

//We check that the moduleName is only alpha characters
if(preg_match('/[^a-z]/',$moduleName)) {
	echo preg_replace(array('/%moduleName%/','/%error%/','/%image%/'),array($moduleName,'only alphabet character for module name',''),$stringForm);
	return;		
}


//We retrieve the file
$filePath = '../app/src/modules/'.$moduleName.'/ressources/logo.png';
if(!is_file($filePath)) {
	echo preg_replace(array('/%moduleName%/','/%error%/','/%image%/'),array($moduleName,'logo not found at '.$filePath,''),$stringForm);
	return;	
}

//We load the bg
if(!$resAsFile) {
	echo preg_replace(array('/%moduleName%/','/%error%/','/%image%/'),array($moduleName,'','<img src="miniLogoGenerator.php?module='.$moduleName.'&size='.$size.'&file=on&online=on" />'),$stringForm);
	return;		
}
else {
	$im = @imagecreatefrompng('logo_mini_bg.png');
	imagealphablending($im, true); // setting alpha blending on
	imagesavealpha($im, true); // save alphablending setting (important)
	
	if(!$im){
		echo preg_replace(array('/%moduleName%/','/%error%/','/%image%/'),array($moduleName,'background image not found',''),$stringForm);
		return;	    	
	}
	//We load the image
	
	$imLogo = @imagecreatefrompng($filePath);
	if(!$imLogo){
		echo preg_replace(array('/%moduleName%/','/%error%/','/%image%/'),array($moduleName,'logo image can t be opened',''),$stringForm);
		return;	    	
	}
	//we resample it to 28x28 and put it at 2x2
	list($width, $height) = getimagesize($filePath);
	
	if($size == '24') $center = 4;
	elseif($size == '26') $center = 3;
	else {$size=28;$center = 2;}
	
	imagecopyresampled($im, $imLogo, $center, $center, 0, 0, $size, $size, $width, $height);
	
	
	//we output
	header('Content-type: image/png');
	if($online != 'on') header('Content-Disposition: attachment; filename="logo_mini.png"');
	imagepng($im);
	imagedestroy($im);
}